
//
//  WPGetVideosFromPhotoVC.m
//  获取本地视频列表
//
//  Created by WGP on 2016/11/21.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPGetVideosFromPhotoVC.h"
#import <Photos/Photos.h>
#import "TZVideoPlayerController.h"
#import "TZAssetModel.h"
#import "TZAssetCell.h"

#define videoLength 3
@interface WPGetVideosFromPhotoVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *videosArr;
@property(nonatomic,strong)PHFetchResult *fetchResult;
@property(nonatomic,assign)NSRange range;

@property(nonatomic,strong)UIImagePickerController *pickerController;

@end

@implementation WPGetVideosFromPhotoVC

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"请选择一个低于3分钟的视频上传" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
//    [alertView show];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"视频";
    
    [self collectionView];
    [self setupVideosArr];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doneBtnDidClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(backBtnDidClick)];
}

-(void)setupVideosArr
{
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:fetchOptions];
    NSUInteger count = [fetchResult countOfAssetsWithMediaType:PHAssetMediaTypeVideo];
    if ( count > 0)
    {
        self.range = NSMakeRange(0, count);
        self.fetchResult = fetchResult;
    }
    //PHFetchResult则是一系列图片资源的集合，我们可以利用它提供的遍历方法，来访问我们获取到的所有照片,代码所示是把PHAsset添加到列表的数据源中
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndexesInRange:self.range];
    [self.fetchResult enumerateObjectsAtIndexes:indexSet options:0 usingBlock:^(PHAsset *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj)
        {
//            WPVideoModel *model = [[WPVideoModel alloc] initWithPHAsset:obj];
            TZAssetModel *model = [TZAssetModel modelWithAsset:obj type:TZAssetModelMediaTypeVideo timeLength:[self timeStrWithDurations:obj.duration]];
            model.duration = obj.duration;
            [self.videosArr addObject:model];
        }
    }];
    
    [self.collectionView reloadData];
}

-(UICollectionView *)collectionView
{
    if(_collectionView == nil)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
        [_collectionView registerNib:[UINib nibWithNibName:@"WPVideoCell" bundle:nil] forCellWithReuseIdentifier:@"WPVideoCell"];
        [_collectionView registerClass:[TZAssetCell class] forCellWithReuseIdentifier:@"TZAssetCell"];
        [_collectionView registerClass:[WPNewVideoCell class] forCellWithReuseIdentifier:@"WPNewVideoCell"];
        CGFloat margin = 4;
        CGFloat itemW = (self.view.bounds.size.width - 2 * margin - 4) / 4.0 - margin;
        CGFloat itemH = itemW;
        layout.minimumInteritemSpacing = margin;
        layout.minimumLineSpacing = margin;
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(itemW, itemH);
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

#pragma mark - collectionView的数据源和代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.videosArr.count + 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//    WPVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPVideoCell" forIndexPath:indexPath];
    if (indexPath.item == 0)
    {
        WPNewVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPNewVideoCell" forIndexPath:indexPath];
        return cell;
    }
    else
    {
        TZAssetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZAssetCell" forIndexPath:indexPath];
        
        TZAssetModel *model = self.videosArr[indexPath.item-1];
        cell.model = model;
        
        __weak typeof(cell) weakCell = cell;
//        __weak typeof(self) weakSelf = self;
        
        cell.didSelectPhotoBlock = ^(BOOL isSelected)
        {
            // 1. cancel select / 取消选择
                weakCell.selectPhotoButton.selected = !isSelected;
                model.isSelected = !isSelected;

        };

        return cell;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == 0)
    {
        //录像
        //录制视频
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted
            || authStatus == AVAuthorizationStatusDenied)
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"摄像头已被禁用，您可在设置应用程序中进行开启" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:cancel];
            
            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.mediaTypes = @[(NSString *)kUTTypeMovie];
            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
            picker.videoQuality = UIImagePickerControllerQualityTypeIFrame1280x720; //录像质量
            picker.videoMaximumDuration = videoLength * 60.0f; // 限制视频录制最多不超过5分钟
            
            [self presentViewController:picker animated:YES completion:NULL];
        } else
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"您的设备不支持摄像" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:cancel];
            
            [self presentViewController:alertController animated:YES completion:nil];
            return ;
        }
    }
    else
    {
        TZVideoPlayerController *videoPlayerVc = [[TZVideoPlayerController alloc] init];
        videoPlayerVc.model = self.videosArr[indexPath.item-1];
        [self.navigationController pushViewController:videoPlayerVc animated:YES];
    }
}

#pragma mark - 摄像后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self showWithStatus:@"正在压缩"];
    
    //如果是视频
    NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
    
    AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:sourceURL options:nil];
    CMTime audioDuration = audioAsset.duration;
    float audioDurationSeconds =CMTimeGetSeconds(audioDuration);
    
    // 保存视频
//    UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
    

      //如果是视频
    [self compressedVideoOtherMethodWithURL:sourceURL compressionType:AVAssetExportPresetMediumQuality compressionResultPath:^(BOOL isSaveSuccess, NSString *outPutUrl, CGFloat outPutSize){
    
            [self dismiss];
            if (isSaveSuccess)
            {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"视频压缩后的文件大小为%.2fM,确定上传吗?",outPutSize] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                UIAlertAction *send = [UIAlertAction actionWithTitle:@"发送" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    if([self.delegate respondsToSelector:@selector(WPGetVideosFromCameraWith:videoModel:)])
                    {
                        TZAssetModel *model = [[TZAssetModel alloc] init];
                        model.timeLength = [NSString timeStrWithDurations:audioDurationSeconds];
                        NSString *URLPath = [NSString stringWithFormat:@"file://%@",outPutUrl];
                        model.urlPath = [NSURL URLWithString:URLPath];
                        model.type = TZAssetModelMediaTypeVideo;
                        
                        [self.delegate WPGetVideosFromCameraWith:self videoModel:model];
                    }
                    [picker.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
                }];
                
                [alertController addAction:cancel];
                [alertController addAction:send];
    
                [picker presentViewController:alertController animated:YES completion:nil];
                return ;
            }
            else
            {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"视频压缩失败" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    
                }];
                [alertController addAction:cancel];
    
                [picker presentViewController:alertController animated:YES completion:nil];
            }
        }];
}

-(void)compressedVideoOtherMethodWithURL:(NSURL *)url compressionType:(NSString *)compressionType compressionResultPath:(void(^)(BOOL isSaveSuccess, NSString * outPutUrl, CGFloat outPutSize))resultPathBlock {
    
    NSString *resultPath;
    
//    NSData *data = [NSData dataWithContentsOfURL:url];
//    CGFloat totalSize = (float)data.length / 1024 / 1024;
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:compressionType];
    
    //保存至沙盒路径
    NSString *pathDocuments = [documentPath stringByAppendingPathComponent:@"WBWYVideos"];
    
    BOOL isDir = NO;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:pathDocuments isDirectory:&isDir];
    if (!isExist || (isExist && !isDir))
    {
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:pathDocuments withIntermediateDirectories:YES attributes:nil error:&error];
        if (error == nil)
        {
            WPLog(@"目录创建成功");
        } else
        {
            WPLog(@"目录创建失败");
        }
    }
    
    // 用时间, 给文件重新命名, 防止视频存储覆盖
    resultPath = [pathDocuments stringByAppendingPathComponent:[NSString stringWithFormat:@"outputJFVideo-%@.mp4", [[WPDateFormatterManager sharedManager] stringFromDateWithDate:[NSDate date] format:@"yyyy-MM-dd-HH:mm:ss"]]];
    
    exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
    
    exportSession.outputFileType = AVFileTypeMPEG4;
    
    exportSession.shouldOptimizeForNetworkUse = YES;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     
     {
         if (exportSession.status == AVAssetExportSessionStatusCompleted)
         {
             
             NSData *data = [NSData dataWithContentsOfFile:resultPath];
             
             float memorySize = (float)data.length / 1024 / 1024;
             
             resultPathBlock(YES,resultPath,memorySize);
             
         } else
         {
             
             resultPathBlock(NO,nil,0.0);
         }
         
     }];
}


// 视频保存回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    
    if (!error)
    {
        [self.videosArr removeAllObjects];
        [self setupVideosArr];
        [self dismiss];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [self showErrorInfoWithStatus:@"视频保存失败"];
    }
    
}

-(NSString *)timeStrWithDurations:(NSTimeInterval)length
{
    int seconds = (int)(length + 0.5);
    
    if (seconds < 60)
    {
        int second = seconds;
        return [NSString stringWithFormat:@"00:%02zd",second];
    }
    else if(seconds <3600)
    {
        int minute = seconds / 60;
        int second = (int)seconds % 60;
        return [NSString stringWithFormat:@"%02zd:%02zd",minute,second];
    }
    else
    {
        int hour = seconds / 3600;
        int minute = ((int)seconds % 3600) / 60;
        int second = (int)seconds % 60;
        return [NSString stringWithFormat:@"%02zd:%02zd:%02zd",hour,minute,second];
    }
}

-(void)doneBtnDidClick
{
    NSMutableArray *videosArr = [NSMutableArray array];
    
    for (TZAssetModel *model in self.videosArr)
    {
        if(model.isSelected)
        {
            [videosArr addObject:model];
        }
    }
    
    if (!videosArr.count)
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"请选择需要上传的视频" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:sure];
        [self presentViewController:alertController animated:YES completion:nil];
        return ;
    }
    
    if (videosArr.count > 1)
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"一次最多只能选择一个视频上传" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:sure];
        [self presentViewController:alertController animated:YES completion:nil];
        return ;
    }
    
    TZAssetModel *model = videosArr[0];
    if(model.duration > 180.0)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"请选择一个低于3分钟的视频上传" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alertView show];
        return ;
    }
    
    //转圈圈
    [self showWithStatus:@"正在压缩"];
    //如果是视频
    [self compressedVideoOtherMethodWithURL:[videosArr[0] urlPath] compressionType:AVAssetExportPresetMediumQuality compressionResultPath:^(BOOL isSaveSuccess, NSString *outPutUrl, CGFloat outPutSize){
        
        [self dismiss];
        if (isSaveSuccess)
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"视频压缩后的文件大小为%.2fM,确定上传吗?",outPutSize] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertAction *send = [UIAlertAction actionWithTitle:@"发送" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                if ([self.delegate respondsToSelector:@selector(WPGetVideosFromPhotoVCDoneWith:videos:)])
                {
                    TZAssetModel *model = videosArr[0];
                    NSString *URLPath = [NSString stringWithFormat:@"file://%@",outPutUrl];
                    model.urlPath = [NSURL URLWithString:URLPath];
                    [self.delegate WPGetVideosFromPhotoVCDoneWith:self videos:videosArr];
                }
                
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            
            [alertController addAction:cancel];
            [alertController addAction:send];
            
            [self presentViewController:alertController animated:YES completion:nil];
            return ;
        }
        else
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"视频压缩失败" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:cancel];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }];
    
}

-(void)backBtnDidClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(NSMutableArray *)videosArr
{
    if (_videosArr == nil)
    {
        _videosArr = [NSMutableArray array];
    }
    return _videosArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)dealloc
{
    NSLog(@"控制器死了");
}

@end




@implementation WPNewVideoCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"video_icon"]];
        _imageView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.500];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:_imageView];
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _imageView.frame = self.bounds;
}

@end







